<template>
  <div class="practice-course">
    <dl>
      <dt>
        <span
          v-for="(tab,index) in tabList"
          :key="index"
          :class="{active: currentTabIndex==index}"
          @click="handleTabClick(tab,index)"
        >{{ tab.title }}</span>
      </dt>

      <div v-if="currentTabIndex === 1" class="avatar-container">

        <el-upload
                style="border: 1px dashed #d9d9d9;width: 178px;height: 178px;"
                class="avatar-uploader"
                :action="BASE_API +'/oss/user/file/upload?host=avatar'"
                :show-file-list="false"
                accept=".jpg"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
          <img v-if="userInfo.avatar" :src="userInfo.avatar" class="avatar" >
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <div slot="tip" class="el-upload__tip">只能上传JPG图片，且不超过1MB</div>

        <div class="avatar-btn">
          <el-button size="medium" type="danger" @click="submitUpload">确认修改</el-button>
          <el-button slot="trigger" size="medium" type="primary" @click="cancelUpload">取消修改</el-button>
        </div>
      </div>


      <div v-if="currentTabIndex === 0" class="info-container">
        <dl>
          <dd class="info-item">
            <div class="info-type">
              昵称
            </div>
            <div class="info-content">
              {{user.nickname}}
            </div>
          </dd>

          <dd class="info-item">
            <div class="info-type">
              电子邮箱
            </div>
            <div class="info-content">
              {{user.email}}
            </div>
          </dd>

          <dd class="info-item">
            <div class="info-type">
              性别
            </div>
            <div class="info-content" v-if="user.sex === 0">
              {{`男`}}
            </div>
            <div class="info-content" v-if="user.sex === 1">
              {{`女`}}
            </div>
            <div class="info-content" v-if="user.sex === 2">
              {{`保密`}}
            </div>
          </dd>
        </dl>

        <el-button class="info-button" @click="editInfo">修改个人信息</el-button>
      </div>

    </dl>

    <!-- 修改个人信息表单 -->
    <InfoForm ref="infoForm" onSaveSuccess="fetchData" />
  </div>
</template>
<script>
import { updateAvatar, cancelUpdateAvatar,getUserById } from '@/api/user';
import { mapGetters } from 'vuex';
import { setToken,removeToken } from '@/utils/cache';

export default {
  inject: ['reload'],
  data () {
    return {
      currentTabIndex: 0, // 当前选项卡的索引
      tabList: [], // 选项卡数据
      BASE_API: process.env.VUE_APP_BASE_API,  //oss地址
      userInfo:{
        id: '',
        avatar: ''
      },
      user:{}
    }
  },
  created () {
    // 初始化选项卡数据
    this.tabList = [
      { title: '个人信息', type: 0 },
      { title: '修改头像', type: 1 },
    ]
    this.getUserInfo()
  },
  methods: {
    // 选项卡点击事件
    handleTabClick (tab, index) {
      this.currentTabIndex = index
    },
    handleAvatarSuccess(res, file) {
      this.userInfo.avatar = res.data.item.url
      this.$message({
        type: 'success',
        message: '上传成功！'
      })
    },

    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt1M = file.size / 1024 / 1024 < 1;

      if (!isJPG) {
        this.$message.error('上传头像只能是 JPG 格式！');
      }
      if (!isLt1M) {
        this.$message.error('上传头像大小不能超过 1MB！');
      }
      return isJPG && isLt1M;
    },

    //确定上传
    submitUpload(){
      if (!this.userInfo.avatar){
        this.$message({
          type: 'error',
          message: '请先上传头像！'
        })
        return;
      }
      this.userInfo.id = this.userId
      updateAvatar(this.$qs.stringify(this.userInfo)).then(result => {
        let { code, data } = result
        if (code === 20000) {
          removeToken()
          setToken(data.token)
          // 重载页面
          window.location.reload()
          this.$message({
            type: 'success',
            message: '修改头像成功！'
          })
        }
      })
    },

    //取消上传
    cancelUpload(){
      if (!this.userInfo.avatar){
        this.$message({
          type: 'error',
          message: '请先上传头像！'
        })
        return;
      }
      this.userInfo.id = this.userId
      cancelUpdateAvatar(this.$qs.stringify(this.userInfo)).then(result => {
        let { code, data } = result
        if (code === 20000) {
          this.reload()
          this.$message({
            type: 'info',
            message: '已取消修改！'
          })
        }
      })
    },

    getUserInfo(){
      getUserById(this.userId).then(result => {
        let {code,data} = result
        if (code === 20000){
          this.user = data.item
        }
      })
    },

    fetchData(){
      this.reload()
    },

    editInfo(){
      this.$refs.infoForm.open()
    }
  },

  computed: {
    ...mapGetters({
      'userId': 'id'
    })
  },
  components:{
    InfoForm: () => import('@/pages/user-center/info-form')
  }
}
</script>
<style lang="stylus" scoped>
  .practice-course
    .avatar-container
      margin 20px 35%
    .avatar-uploader .el-upload
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    .avatar-uploader .el-upload:hover
      border-color: #409EFF;
    .avatar-uploader-icon
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    .avatar
      width: 178px;
      height: 178px;
      object-fit cover;
      display: block;
    .el-upload__tip
      margin-left 5px
    .avatar-btn
      margin-top 15px
      margin-left -8px
    dt
      border-bottom: 1px solid #d0d6d9;
      & > span
        margin-right: 48px;
        display: inline-block;
        vertical-align: middle;
        height: 48px;
        line-height: 48px;
        box-sizing: border-box;
        font-size: 14px;
        color: #787d82
        cursor: pointer;
        &:last-child
          margin-right: 0;
        &.active
          color: #f01414;
          border-bottom: 2px solid #f01414;
  .el-button--danger{
    background-color: #f01414;
    border: #f01414;
  }
  .info-title{
    margin-bottom: 24px;
    height: 48px;
    border-bottom: 1px solid #d0d6d9;
    line-height: 48px;
    font-size: 16px;
    font-weight: 700;
    color: #333;
  }
  .info-item{
    display: flex;
    align-items: center;
    margin-bottom: 20px;
  }
  .info-type{
    flex: 0 0 120px;
    width: 120px;
    padding: 20px 0;
    margin-right: 20px;
    font-size: 14px;
    color: #07111b;
    font-weight: 700;
    background-color: #f3f5f7;
    text-align: center;
  }
  .info-content{
    flex: 1;
    padding: 20px 0;
    border-bottom: 1px solid #d9dde1;
    font-size: 14px;
  }
  .info-container{
    margin-top 10px
  }
  .info-button{
    float right;
    color: #FFFFFF;
    background-color: #ef1514;
    border-color #ef1514;
  }
</style>
